package command.client;

import client.ClientSession;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Message;
import model.MessageCommunication;

public class SendMessageClient implements CommandClient {

    private String conversationID;
    private Message message;

    public SendMessageClient() {
    }

    public void setConversationID(String idOfTheConversation) {
        conversationID = idOfTheConversation;
    }

    public void setMessage(Message messageOfTheChat) {
        message = messageOfTheChat;
    }

    @Override
    public void execute(ClientSession clientSession, boolean isInvokedByTheServer) {
        try {
            if (isInvokedByTheServer) {
                MessageCommunication conversation = (MessageCommunication) clientSession.getObjectInputStream().
                        readObject();
                Message messageToAdd = (Message) clientSession.getObjectInputStream().readObject();
                clientSession.getGUIChatPrincipal().getConversations().get(conversation.getMessage()).
                        addMessageToConversation(messageToAdd);
            } else {
                clientSession.getObjectOutputStream().writeObject(
                        new MessageCommunication(true, "sendmessageserver"));
                clientSession.getObjectOutputStream().flush();
                clientSession.getObjectOutputStream().writeObject(
                        new MessageCommunication(true, conversationID));
                clientSession.getObjectOutputStream().flush();
                clientSession.getObjectOutputStream().writeObject(message);
                clientSession.getObjectOutputStream().flush();
            }
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(SendMessageClient.class.getName()).log(Level.SEVERE,
                    "Fallo al realizar el envío y recepción de nuevo mensaje de la conversación en el Cliente", ex);
        }
    }
}
